package com.plugin.manage.service.impl;

import com.plugin.core.model.entity.ElderDish;
import com.plugin.core.model.entity.ElderMealSet;
import com.plugin.manage.common.RespObj;
import com.plugin.manage.mapper.MealsMapper;
import com.plugin.manage.service.IMealsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.util.*;

/**
 * 用餐看板服务实现类
 *
 * @author mark
 * @date 2025-07-26
 */
@Slf4j
@Service
public class MealsServiceImpl implements IMealsService {

    @Autowired
    private MealsMapper mealsMapper;

    @Override
    public RespObj<?> getMealStatistics() {
        try {
            log.info("开始查询用餐统计信息");

            // 获取今日用餐人数
            Long todayCount = mealsMapper.countTodayMeals();
            if (todayCount == null) {
                todayCount = 0L;
            }

            // 构建返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("todayMealCount", todayCount);

            log.info("用餐统计查询成功，今日：{}人", todayCount);

            return new RespObj<>().success(result);

        } catch (Exception e) {
            log.error("查询用餐统计信息失败", e);
            return new RespObj<>().failure("查询用餐统计信息失败: " + e.getMessage());
        }
    }

    @Override
    public RespObj<?> getTodayMenuRecords() {
        try {
            log.info("开始查询今日菜谱记录");

            // 查询今日菜谱记录
            java.util.List<ElderDish> records =
                    mealsMapper.getTodayMenuRecords();

            // 构建返回结果
            java.util.Map<String, Object> result = new java.util.HashMap<>();
            result.put("records", records);
            result.put("totalCount", records.size());
            result.put("queryDate", java.time.LocalDate.now().toString());

            log.info("今日菜谱记录查询成功，共{}条记录", records.size());

            return new RespObj<>().success(result);

        } catch (Exception e) {
            log.error("查询今日菜谱记录失败", e);
            return new RespObj<>().failure("查询今日菜谱记录失败: " + e.getMessage());
        }
    }

    @Override
    public RespObj<?> getLast7DaysMealStatistics() {
        try {
            log.info("开始统计最近7天就餐人次");

            // 查询最近7天的就餐人次数据
            java.util.List<java.util.Map<String, Object>> rawData =
                    mealsMapper.getLast7DaysMealCounts();

            // 生成最近7天的日期列表（保证数据完整性）
            java.util.List<String> last7Days = new java.util.ArrayList<>();
            java.util.List<Integer> mealCounts = new java.util.ArrayList<>();

            java.time.LocalDate today = java.time.LocalDate.now();
            for (int i = 6; i >= 0; i--) {
                java.time.LocalDate date = today.minusDays(i);
                String dateStr = date.toString();
                last7Days.add(dateStr);

                // 查找对应日期的数据
                int count = 0;
                for (java.util.Map<String, Object> data : rawData) {
                    String mealDate = data.get("meal_date").toString();
                    if (dateStr.equals(mealDate)) {
                        count = ((Number) data.get("meal_count")).intValue();
                        break;
                    }
                }
                mealCounts.add(count);
            }

            // 计算统计数据
            int totalMeals = mealCounts.stream().mapToInt(Integer::intValue).sum();
            double averageMeals = totalMeals / 7.0;
            int maxMeals = mealCounts.stream().mapToInt(Integer::intValue).max().orElse(0);
            int minMeals = mealCounts.stream().mapToInt(Integer::intValue).min().orElse(0);

            // 构建返回结果
            java.util.Map<String, Object> result = new java.util.HashMap<>();
            result.put("dates", last7Days);
            result.put("mealCounts", mealCounts);
            result.put("totalMeals", totalMeals);
            result.put("averageMeals", new BigDecimal(averageMeals).setScale(1, RoundingMode.HALF_UP));
            result.put("maxMeals", maxMeals);
            result.put("minMeals", minMeals);
            result.put("statisticsDate", today.toString());

            log.info("最近7天就餐人次统计成功，总计{}人次，平均{}人次/天",
                    totalMeals, averageMeals);

            return new RespObj<>().success(result);

        } catch (Exception e) {
            log.error("统计最近7天就餐人次失败", e);
            return new RespObj<>().failure("统计最近7天就餐人次失败: " + e.getMessage());
        }
    }

    @Override
    public RespObj<?> getTodayMenu() {
        try {
            log.info("开始根据parent_id查询今日套餐菜谱，: {}");

            // 查询指定parent_id的套餐菜谱
            java.util.List<ElderMealSet> categories =
                    mealsMapper.getTodayMenu();

            // 构建返回结果
            java.util.Map<String, Object> result = new java.util.HashMap<>();
            result.put("categories", categories);
            result.put("totalCount", categories.size());
            result.put("queryDate", java.time.LocalDate.now().toString());

            log.info("根据查询今日套餐菜谱成功，共{}个菜品", categories.size());

            return new RespObj<>().success(result);

        } catch (Exception e) {
            log.error("根据查询今日套餐菜谱失败", e);
            return new RespObj<>().failure("根据查询今日套餐菜谱失败: " + e.getMessage());
        }
    }


    @Override
    public RespObj<?> getTodayDinnerModeStatistics() {
        try {
            log.info("开始统计今日就餐方式数量");

            // 查询今日就餐方式统计数据
            List<Map<String, Object>> rawData =
                    mealsMapper.getTodayDinnerModeStatistics();

            // 初始化统计数据（默认值为0）
            Map<String, Integer> modeStatistics = new LinkedHashMap<>();
            modeStatistics.put("堂食", 1);  // dinner_mode = 1
            modeStatistics.put("外带", 2);  // dinner_mode = 2
            modeStatistics.put("送餐", 3);  // dinner_mode = 3

            // 处理查询结果
            int totalCount = 0;
            for (Map<String, Object> data : rawData) {
                Integer dinnerMode = ((Number) data.get("dinner_mode")).intValue();
                Integer count = ((Number) data.get("count")).intValue();
                totalCount += count;

                switch (dinnerMode) {
                    case 1:
                        modeStatistics.put("堂食", count);
                        break;
                    case 2:
                        modeStatistics.put("外带", count);
                        break;
                    case 3:
                        modeStatistics.put("送餐", count);
                        break;
                    default:
                        log.warn("未知的就餐方式: {}", dinnerMode);
                        break;
                }
            }

            // 构建返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("modeStatistics", modeStatistics);
            result.put("totalCount", totalCount);
            result.put("queryDate", LocalDate.now().toString());
            result.put("rawData", rawData); // 原始数据供参考

            // 计算百分比
            Map<String, String> percentages = new HashMap<>();
            if (totalCount > 0) {
                for (Map.Entry<String, Integer> entry : modeStatistics.entrySet()) {
                    double percentage = (entry.getValue() * 100.0) / totalCount;
                    percentages.put(entry.getKey(), String.format("%.1f%%", percentage));
                }
            }
            result.put("percentages", percentages);

            log.info("今日就餐方式统计成功，总计{}人次，堂食{}人次，外带{}人次，送餐{}人次", 
                    totalCount, modeStatistics.get("堂食"), modeStatistics.get("外带"), modeStatistics.get("送餐"));

            return new RespObj<>().success(result);

        } catch (Exception e) {
            log.error("统计今日就餐方式数量失败", e);
            return new RespObj<>().failure("统计今日就餐方式数量失败: " + e.getMessage());
        }
    }

    @Override
    public RespObj<?> getTodayDishCategoryStatistics() {
        try {
            log.info("开始统计今日菜品分类数量和百分比（统计每个菜品ID被售卖的总次数，按分类计算比值）");

            // 查询今日菜品分类统计数据（统计dish_ids中每个菜品ID在今天被售卖的总次数）
            List<Map<String, Object>> rawData =
                    mealsMapper.getTodayDishCategoryStatistics();

            if (rawData == null || rawData.isEmpty()) {
                log.info("今日暂无菜品分类数据");
                Map<String, Object> result = new HashMap<>();
                result.put("categoryStatistics", new HashMap<>());
                result.put("totalCount", 0);
                result.put("queryDate", LocalDate.now().toString());
                return new RespObj<>().success(result);
            }

            // 处理统计数据
            Map<String, Integer> categoryStatistics = new LinkedHashMap<>();
            int totalCount = 0;

            for (Map<String, Object> data : rawData) {
                String categoryName = (String) data.get("category_name");
                Integer count = ((Number) data.get("count")).intValue();
                
                if (categoryName != null) {
                    categoryStatistics.put(categoryName, count);
                    totalCount += count;
                }
            }

            // 构建返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("categoryStatistics", categoryStatistics);
            result.put("totalCount", totalCount);
            result.put("queryDate", LocalDate.now().toString());
            result.put("rawData", rawData); // 原始数据供参考

            // 构建详细统计信息
            List<Map<String, Object>> detailStatistics = new ArrayList<>();
            for (Map.Entry<String, Integer> entry : categoryStatistics.entrySet()) {
                Map<String, Object> detail = new HashMap<>();
                detail.put("categoryName", entry.getKey());
                detail.put("count", entry.getValue());
                detailStatistics.add(detail);
            }
            result.put("detailStatistics", detailStatistics);

            log.info("今日菜品分类统计成功（菜品售卖次数统计），总计{}次售卖，共{}个分类", 
                    totalCount, categoryStatistics.size());

            return new RespObj<>().success(result);

        } catch (Exception e) {
            log.error("统计今日菜品分类数量失败", e);
            return new RespObj<>().failure("统计今日菜品分类数量失败: " + e.getMessage());
        }
    }

    @Override
    public RespObj<?> getTodayDishConsumptionTop5() {
        try {
            log.info("开始统计今日菜品消费份数TOP5");

            // 查询今日菜品消费份数TOP5数据
            List<Map<String, Object>> rawData =
                    mealsMapper.getTodayDishConsumptionTop5();

            if (rawData == null || rawData.isEmpty()) {
                log.info("今日暂无菜品消费数据");
                Map<String, Object> result = new HashMap<>();
                result.put("top5List", new ArrayList<>());
                result.put("totalDishes", 0);
                result.put("queryDate", LocalDate.now().toString());
                return new RespObj<>().success(result);
            }

            // 处理TOP5数据
            List<Map<String, Object>> top5List = new ArrayList<>();
            int totalConsumption = 0;

            for (int i = 0; i < rawData.size(); i++) {
                Map<String, Object> data = rawData.get(i);
                Long dishId = ((Number) data.get("id")).longValue();
                String dishName = (String) data.get("dish_name");
                Integer count = ((Number) data.get("count")).intValue();
                
                Map<String, Object> dishInfo = new HashMap<>();
                dishInfo.put("rank", i + 1);
                dishInfo.put("dishId", dishId);
                dishInfo.put("dishName", dishName);
                dishInfo.put("consumptionCount", count);
                
                top5List.add(dishInfo);
                totalConsumption += count;
            }

            // 构建返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("top5List", top5List);
            result.put("totalDishes", rawData.size());
            result.put("totalConsumption", totalConsumption);
            result.put("queryDate", LocalDate.now().toString());
            result.put("rawData", rawData); // 原始数据供参考

            log.info("今日菜品消费份数TOP5统计成功，共{}道菜参与排名，总消费{}份", 
                    rawData.size(), totalConsumption);

            return new RespObj<>().success(result);

        } catch (Exception e) {
            log.error("统计今日菜品消费份数TOP5失败", e);
            return new RespObj<>().failure("统计今日菜品消费份数TOP5失败: " + e.getMessage());
        }
    }

    @Override
    public RespObj<?> getTodayMealSetTop5() {
        try {
            log.info("开始统计今日套餐消费次数TOP5");

            // 查询今日套餐消费次数TOP5数据
            List<Map<String, Object>> rawData =
                    mealsMapper.getTodayMealSetTop5();

            if (rawData == null || rawData.isEmpty()) {
                log.info("今日暂无套餐消费数据");
                Map<String, Object> result = new HashMap<>();
                result.put("top5List", new ArrayList<>());
                result.put("totalMealSets", 0);
                result.put("queryDate", LocalDate.now().toString());
                return new RespObj<>().success(result);
            }

            // 处理TOP5数据
            List<Map<String, Object>> top5List = new ArrayList<>();
            int totalConsumption = 0;

            for (int i = 0; i < rawData.size(); i++) {
                Map<String, Object> data = rawData.get(i);
                String setName = (String) data.get("dish_name");
                Integer count = ((Number) data.get("count")).intValue();
                
                Map<String, Object> mealSetInfo = new HashMap<>();
                mealSetInfo.put("rank", i + 1);
                mealSetInfo.put("setName", setName != null ? setName : "未知套餐");
                mealSetInfo.put("consumptionCount", count);
                
                top5List.add(mealSetInfo);
                totalConsumption += count;
            }

            // 构建返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("top5List", top5List);
            result.put("totalMealSets", rawData.size());
            result.put("totalConsumption", totalConsumption);
            result.put("queryDate", LocalDate.now().toString());
            result.put("rawData", rawData); // 原始数据供参考

            log.info("今日套餐消费次数TOP5统计成功，共{}个套餐参与排名，总消费{}次", 
                    rawData.size(), totalConsumption);

            return new RespObj<>().success(result);

        } catch (Exception e) {
            log.error("统计今日套餐消费次数TOP5失败", e);
            return new RespObj<>().failure("统计今日套餐消费次数TOP5失败: " + e.getMessage());
        }
    }
}
